package com.sh.data.engine.domain.datadev.offline.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import com.sh.data.engine.domain.datadev.offline.service.DatadevMenuNodeService;
import com.sh.data.engine.domain.datadev.offline.service.DatadevSubNodeDependencyService;
import com.sh.data.engine.domain.datadev.offline.service.DatadevSubNodeService;
import com.sh.data.engine.repository.dao.datadev.DatadevSubNodeMapper;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevMenuNodeEntity;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevSubNodeDependencyEntity;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevSubNodeEntity;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class DatadevSubNodeServiceImpl
    extends ServiceImpl<DatadevSubNodeMapper, DatadevSubNodeEntity>
    implements DatadevSubNodeService {

    @Lazy
    @Autowired
    private DatadevMenuNodeService datadevMenuNodeService;

    @Lazy
    @Autowired
    private DatadevSubNodeDependencyService datadevSubNodeDependencyService;

    @Override
    public List<DatadevSubNodeEntity> getDatadevSubNodeList(Long taskFlowId) {

        List<DatadevSubNodeEntity> subTaskList =
            list(
                new LambdaQueryWrapper<DatadevSubNodeEntity>()
                    .eq(DatadevSubNodeEntity::getTaskFlowId, taskFlowId)
                    .orderByAsc(DatadevSubNodeEntity::getNodeId));
        return subTaskList;
    }

    @Override
    public boolean checkTaskFlowContainTaskType(Long flowId, List<Integer> nodeType) {
        List<DatadevSubNodeDependencyEntity> datadevSubNodeDepenDencyList =
            datadevSubNodeDependencyService.getDatadevSubNodeDepenDencyList(flowId);

        Set<Long> ids = Sets.newHashSet();
        datadevSubNodeDepenDencyList.forEach(
            e -> {
                ids.add(e.getDownNodeId());
                ids.add(e.getUpNodeId());
            });

        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        List<DatadevMenuNodeEntity> datadevMenuNodeEntities = datadevMenuNodeService.listByIds(ids);

        for (DatadevMenuNodeEntity menuNodeEntity : datadevMenuNodeEntities) {
            if (nodeType.contains(menuNodeEntity.getNodeType())) {
                return true;
            }
        }
        return false;
    }
}
